package com.sky.service.impl;

import com.sky.constant.BaseContext;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.OrderService;
import com.sky.vo.OrderSubmitVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private HttpServletRequest request;

    @Transactional
    @Override
    public OrderSubmitVO submit(Orders orders) {
        /*
        1 购物车 -> 订单（orders + order_detail）
        2 清理购物车
         */
        //1: 获取购物车->userId->token->请求头

        Long userId = BaseContext.getUserId();
        log.info("baseContext获取到的userId:{}",userId);

        List<ShoppingCart> shoppingCarts= shoppingCartMapper.getByUserId(userId);
        log.info("cart:{}",shoppingCarts);
        //2:购物车->订单
        orders.setNumber(UUID.randomUUID().toString().replace("-",""));
        orders.setStatus(1);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(0);
        orders.setUserId(userId);
        //5:先写入orders -> order_id
        orderMapper.insert(orders);
        //3:购物车->订单详情表
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            //4：缺少order_id -> orders提供
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.add(orderDetail);
        }

        //6:清理购物车
        shoppingCartMapper.deleteByUserId(userId);
        //7:组装返回值vo
        OrderSubmitVO vo=new OrderSubmitVO();
        //从订单的自增id
        vo.setId(orders.getId());
        //从订单获取->时间戳
        vo.setOrderNumber(orders.getNumber());
        vo.setOrderAmount(orders.getAmount());
        vo.setOrderTime(orders.getOrderTime());
        return vo;
    }
}
